package com.celi.scs.common.utils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @project: bg-scs
 * @title: RSAEncryption
 * @author: lihq
 * @date: 2024/11/15 14:15
 * @version: v1.0
 * @description: RSA加密
 */
public class RSAUtil {

    /**
     * 公钥加密
     * @param password  原密码
     * @param publicKey 公钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String password, String publicKey) throws Exception {
        // 获取公钥
        byte[] publicBytes = Base64.getDecoder().decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(keySpec);

        // 使用公钥加密数据
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encryptedData = cipher.doFinal(password.getBytes());

        // 返回加密后的数据
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    public static void main(String[] args) throws Exception {
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCq/tBY/aMASbuVcWmnoBvDUoc2p9tST5vDREeh2sSBydul79UZjxwSldSXyG36ICbmULMqN3Q1gC13ax95QR3DUEGepFJRlfmoxQlwccLOgypmP7HvnoWeTAW/swYWB2aofdve/Ni8bKaD6hyLjg6OOuP06MG76J7644HrbomjBwIDAQAB";
        String password = "Qlj@780411";

        // 使用公钥加密密码
        String encryptedPassword = RSAUtil.encrypt(password, publicKey);
        System.out.println("encryptedPassword: " + encryptedPassword);
    }

}
